package channel;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.net.URL;
import server.util.ServerConstants;

/**
 *
 * @author Michael Hanns
 *
 */
class ChannelItem {

    private Socket socket;
    private int port;
    private String serverName;
    private String advName;
    private String advDesc;
    private double advVers;
    private int maxPlayers;
    private int currentPlayers;

    public ChannelItem(Socket s, int port, String serverName, String advName,
            String advDesc, double advVers, int maxPlayers) {
        this.socket = s;
        this.serverName = serverName;
        this.advName = advName;
        this.advDesc = advDesc;
        this.advVers = advVers;
        this.maxPlayers = maxPlayers;
        this.currentPlayers = 0;
        this.port = port;
    }

    public String getServerName() {
        return serverName;
    }

    public int getServerPort() {
        return port;
    }

    public String getAdvName() {
        return advName;
    }

    public String getAdvDesc() {
        return advDesc;
    }

    public double getAdvVers() {
        return advVers;
    }

    public String getIP() {
        if (socket.getInetAddress().getHostAddress().equals("127.0.0.1")) {
            try {
                URL whatismyip = new URL(ServerConstants.externalIPAddr);
                InputStream stream = whatismyip.openStream();
                BufferedReader in = new BufferedReader(new InputStreamReader(stream));

                String ip = in.readLine();
                stream.close();
                in.close();

                if (ip != null && ip.length() > 0) {
                    return ip;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return socket.getInetAddress().getHostAddress();
    }

    public int getMaxPlayers() {
        return maxPlayers;
    }

    public int getCurrentPlayers() {
        return currentPlayers;
    }

    public void addPlayer() {
        currentPlayers++;
    }

    public void removePlayer() {
        currentPlayers--;
    }

    public void setPlayerCount(int p) {
        currentPlayers = p;
    }

    public boolean isConnected() {
        return socket.isConnected();
    }
}
